/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package maindatart.rush.alg;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import maindatart.rush.result.RushResultService;

/**
 *  zhangxu
 * 比较两个文本的相似性
 * 
 * 算法描述：
 *  按照单字进行匹配
 *  顺序匹配
 * 
 *  将两个文本都拆解为顺序的单字 
 * 
 *      以较文本为准，顺序抽取较短文本中的文字，逐项比对，比对成功则设定游标指定位置，后续文字从游标位置向后继续比对。
 *      最终以比对上字符数量与总字符数量比重
 * 
 * @author Administrator
 */
public class TextSameAlt implements DataSameAlgorithm {

    private static TextSameAlt s = null;
    
    private TextSameAlt(){
        
    }
    
    public static TextSameAlt getInstance(){
        if(s == null){
            s = new TextSameAlt();
        }
        return s;
    }
    
    @Override
    public double itemSame(Object a, Object b) {
        List<Character> rithtCharacter = new ArrayList();
       
        if(a == null || b== null)
            return 0;
        
        try{
            String aa = (String)a;
            String bb = (String)b;
            List<Character> longchar;
            List<Character> shortchar;
            if(aa.length() > bb.length()){
                longchar = this.stringToVector(aa);
                shortchar = this.stringToVector(bb);
            }else{
                longchar = this.stringToVector(bb);
                shortchar = this.stringToVector(aa);
            }
            for(char one : shortchar){
                
                for(int i = 0;i < longchar.size();i ++){
                    char other = longchar.get(i);
                    if(other == one){
                        rithtCharacter.add(one);
                        longchar = longchar.subList(i, longchar.size());
                        break;
                    }
                }
            }
            
            return (double)rithtCharacter.size() / (double)longchar.size();
        }catch(Throwable t){
            Logger.getLogger(RushResultService.class.getName()).log(Level.SEVERE, null, t);
        }
        return 0;
    }
    
    
    private List<Character> stringToVector(String string){
        char[] charArray = string.toCharArray();
        List<Character> v = new ArrayList();
        for(char c : charArray){
            v.add(c);
        }
        return v;
    }
   
    
       @Override
    public String getDescrip() {
        return "字符完全匹配算法";
    }
    
    
    public static void main(String args[]){
        TextSameAlt tsa = TextSameAlt.getInstance();
        String a = "北京的用友";
        String b = "北京用友软件";
        double d = tsa.itemSame(a, b);
        System.out.println(d);
    }
    
}
